import { PassportStrategy } from "@nestjs/passport"
import { IStrategyOptions, Strategy } from "passport-local"
import { UserEntity } from '../user/entities/user.entity'
import { InjectRepository } from "@nestjs/typeorm"
import { Repository } from "typeorm"
import { BadRequestException } from "@nestjs/common"
import { validatePwd } from "utils/crypt"

export class LocalStorage extends PassportStrategy (Strategy) {
  constructor(
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity> // 注入User实体类的Repository
  ){
    super({
      usernameField: 'username',
      passwordField: 'password'
    } as IStrategyOptions)
  }

  async validate(username: string, password: string): Promise<any> {
    const user = await this.userRepository
      .createQueryBuilder("user")
      .addSelect("user.username")
      .where("user.username = :username", { username })
      .getOne()
    if (!user) {
      throw new BadRequestException('用户名不正确！')
    }
    if (!validatePwd(password, user.password)) {
      throw new Error('密码不正确')
    }
    return user
  }
}